package com.ruoyi.safe.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.*;
import com.ruoyi.safe.domain.*;
import com.ruoyi.safe.domain.vo.BizEducateDocAttachVO;
import com.ruoyi.safe.domain.vo.BizEducateVO;
import com.ruoyi.safe.mapper.BizEducateDocAttachMapper;
import com.ruoyi.safe.mapper.BizEducateMapper;
import com.ruoyi.safe.mapper.CommonCooperatorClassMapper;
import com.ruoyi.safe.mapper.CommonCooperatorMapper;
import com.ruoyi.safe.service.IBizEducateDocAttachService;
import com.ruoyi.safe.service.IBizEducateService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 班前教育Service业务层处理
 *
 * @author buxi
 * @date 2023-12-21
 */

@Service
public class BizEducateServiceImpl implements IBizEducateService {

    @Autowired
    BizEducateMapper bizEducateMapper;
    @Autowired
    BizEducateDocAttachMapper bizEducateDocAttachMapper;

    @Autowired
    IBizEducateDocAttachService bizEducateDocAttachService;
    @Autowired
    CommonCooperatorClassMapper commonCooperatorClassMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    CommonCooperatorMapper commonCooperatorMapper;
    /**
     * 查询班前教育
     *
     * @param id 班前教育主键
     * @return 班前教育
     */
    @Override
    public BizEducate selectBizEducateById(Long id) {
        BizEducate bizEducate = bizEducateMapper.selectBizEducateById(id);
        List<BizEducateClass>  bizEducateClassList = bizEducateMapper.selectBizEducateClassByEducateIds(Arrays.asList(id));
        bizEducate.setBizEducateClassList(bizEducateClassList);
        //现场照片
        if (StrUtil.isNotEmpty(bizEducate.getPhotoName())){
            Set<Long> attachIds = Arrays.stream(bizEducate.getPhotoName().split(",")).map(item->Long.valueOf(item)).collect(Collectors.toSet());
            List<BizEducateDocAttachVO> bizEducateDocAttaches = bizEducateDocAttachService.selectBizEducateDocAttachByIds(attachIds.toArray(new Long[]{}));
            bizEducate.setPhotoBizEducateDocAttachList(bizEducateDocAttaches);
        }
        //教育资料
        if (StrUtil.isNotEmpty(bizEducate.getFileName())){
            Set<Long> attachIds = Arrays.stream(bizEducate.getFileName().split(",")).map(item->Long.valueOf(item)).collect(Collectors.toSet());
            List<BizEducateDocAttachVO> bizEducateDocAttaches = bizEducateDocAttachService.selectBizEducateDocAttachByIds(attachIds.toArray(new Long[]{}));
            bizEducate.setFileBizEducateDocAttachList(bizEducateDocAttaches);
        }
        //现场录音
        if (StrUtil.isNotEmpty(bizEducate.getAudio())){
            Set<Long> attachIds = Arrays.stream(bizEducate.getAudio().split(",")).map(item->Long.valueOf(item)).collect(Collectors.toSet());
            List<BizEducateDocAttachVO> bizEducateDocAttaches = bizEducateDocAttachService.selectBizEducateDocAttachByIds(new Long[]{});
            //录音时长
            String audioDuration = bizEducate.getAudioDuration();
            if(StringUtils.isNotEmpty(audioDuration)){
                String[] audioDurations = audioDuration.split(",");
                for (int i = 0; i < bizEducateDocAttaches.size(); i++) {
                    if(i < audioDurations.length){
                        bizEducateDocAttaches.get(i).setAudioDuration(audioDurations[i]);
                    }
                }
            }
            bizEducate.setAudioBizEducateDocAttachList(bizEducateDocAttaches);
        }
        //教育班组信息
        if(bizEducateClassList.size() > 0){
            Set<Long> bizEducateClassIdSet = bizEducateClassList.stream().map(bizEducateClass->bizEducateClass.getClassId()).collect(Collectors.toSet());
            //公司信息
            List<CommonCooperatorClass> commonCooperatorClasses = commonCooperatorClassMapper.selectCommonCooperatorClassByIds(bizEducateClassIdSet);
            Map<Long,CommonCooperatorClass> commonCooperatorClassMap = commonCooperatorClasses.stream().collect(Collectors.toMap(CommonCooperatorClass::getId,Function.identity()));
            List<CommonCooperator> commonCooperators = commonCooperatorMapper.selectSubPackageList();
            Map<Long,CommonCooperator> commonCooperatorMap = commonCooperators.stream().collect(Collectors.toMap(CommonCooperator::getId, Function.identity()));
            bizEducateClassList.forEach(bizEducateClass->{
                CommonCooperatorClass commonCooperatorClass = commonCooperatorClassMap.get(bizEducateClass.getClassId());
                bizEducateClass.setCooperatorClassName(commonCooperatorClass.getClassName());
                CommonCooperator commonCooperator = commonCooperatorMap.get(commonCooperatorClass.getCooperatorId());
                bizEducateClass.setSubPackageCooperatorName(commonCooperator.getEnterpriseName());
                bizEducateClass.setLeaderName(commonCooperatorClass.getLeaderName());
            });
        }
        SysUser sysUser = sysUserMapper.selectUserByUserName(bizEducate.getCreateBy());
        if(sysUser != null){
            bizEducate.setCreateBy(sysUser.getNickName());
        }
        return bizEducate;
    }

    /**
     * 查询班前教育列表
     *
     * @param bizEducate 班前教育
     * @return 班前教育
     */
    @Override
    public List<BizEducateVO> selectBizEducateList(BizEducate bizEducate) {
        //班前教育列表
        PageUtils.startPage();
        List<BizEducate> bizEducates = bizEducateMapper.selectBizEducateList(bizEducate);
        PageUtils.clearPage();

        if(bizEducates.size() > 0){
            Set<String> bizEducateCreateBys = bizEducates.stream().map(item->item.getCreateBy()).collect(Collectors.toSet());
            List<Long> educateIds = bizEducates.stream().map(BizEducate::getId).collect(Collectors.toList());
            //现场照片ID集合
            Set<Long> photoAttachIds = new HashSet<>();
            bizEducates.stream().forEach(item->{
                if(StringUtils.isNotEmpty(item.getPhotoName())){
                    String[] photoIds = item.getPhotoName().split(",");
                    for (int i = 0; i < photoIds.length; i++) {
                        photoAttachIds.add(Long.valueOf(photoIds[i]));
                    }
                }
            });
            Map<Long,BizEducateDocAttach> photoBizEducateDocAttachMap = new HashMap<>();
            if(photoAttachIds.size() > 0){
                //现场照片集合
                List<BizEducateDocAttach> photoBizEducateDocAttaches = bizEducateDocAttachMapper.selectBizEducateDocAttachByIds(photoAttachIds.toArray(new Long[]{}));
                photoBizEducateDocAttachMap.putAll(photoBizEducateDocAttaches.stream().collect(Collectors.toMap(BizEducateDocAttach::getId,Function.identity())));
            }
            //教育班级
            List<BizEducateClass> bizEducateClasses = bizEducateMapper.selectBizEducateClassByEducateIds(educateIds);
            Map<Long,List<BizEducateClass>> bizEducateClassMap = bizEducateClasses.stream().collect(Collectors.groupingBy(BizEducateClass::getEducateId));
            //补充信息
            List<BizEducateVO> bizEducateVOList = bizEducates.stream().map(item -> {
                BizEducateVO bizEducateVO = new BizEducateVO();
                BeanUtil.copyProperties(item, bizEducateVO);
                //补充照片信息
                if(StringUtils.isNotEmpty(item.getPhotoName())){
                    String[] photoAttachIds1 = item.getPhotoName().split(",");
                    List<BizEducateDocAttach> photoBizEducateDocAttaches1 = new ArrayList<>();
                    for (int i = 0; i < photoAttachIds1.length; i++) {
                        String photoAttachId = photoAttachIds1[i];
                        BizEducateDocAttach bizEducateDocAttach = photoBizEducateDocAttachMap.get(Long.valueOf(photoAttachId));
                        if(bizEducateDocAttach != null){
                            photoBizEducateDocAttaches1.add(bizEducateDocAttach);
                        }
                    }
                    int videoCount = photoBizEducateDocAttaches1.stream().filter(photoBizEducateDocAttache->photoBizEducateDocAttache.getType().startsWith("video")).collect(Collectors.toList()).size();
                    int photoCount = photoBizEducateDocAttaches1.stream().filter(photoBizEducateDocAttache->photoBizEducateDocAttache.getType().startsWith("image")).collect(Collectors.toList()).size();
                    bizEducateVO.setPhotoCount(photoCount);
                    bizEducateVO.setVideoCount(videoCount);
                }else{
                    bizEducateVO.setPhotoCount(0);
                    bizEducateVO.setVideoCount(0);
                }
                if(StringUtils.isNotEmpty(item.getAudio())){
                    String[] audioIds = item.getAudio().split(",");
                    bizEducateVO.setAudioCount(audioIds.length);
                }else{
                    bizEducateVO.setAudioCount(0);
                }

                //补充班组信息
                List<BizEducateClass> bizEducateClassList = bizEducateClassMap.get(item.getId());
                if(bizEducateClassList != null &&bizEducateClassList.size() > 0){
                    //班组名字
                    Set<Long> classIds = bizEducateClassList.stream().map(BizEducateClass::getClassId).collect(Collectors.toSet());
                    List<CommonCooperatorClass> commonCooperatorClasses = commonCooperatorClassMapper.selectCommonCooperatorClassByIds(classIds);
                    String classNames = commonCooperatorClasses.stream().map(CommonCooperatorClass::getClassName).collect(Collectors.joining(","));
                    bizEducateVO.setEducateClass(classNames);
                    //应教育人数 应到人数
                    Long shouldEducatePeoples = 0L,practiceEducatePeoples = 0L;
                    for (int i = 0; i < bizEducateClassList.size(); i++) {
                        BizEducateClass bizEducateClass = bizEducateClassList.get(i);
                        if(bizEducateClass.getShouldEducatePeoples() != null) {
                            shouldEducatePeoples += bizEducateClass.getShouldEducatePeoples();
                        }
                        if(bizEducateClass.getPracticeEducatePeoples() != null){
                            practiceEducatePeoples += bizEducateClass.getPracticeEducatePeoples();
                        }
                    }
                    bizEducateVO.setShouldEducatePeoples(shouldEducatePeoples);
                    bizEducateVO.setPracticeEducatePeoples(practiceEducatePeoples);
                }
                return bizEducateVO;
            }).collect(Collectors.toList());
            //补充班前教育创建人
            SysUser sysUser = new SysUser();
            sysUser.setUserNames(bizEducateCreateBys);
            NameUtils.handleUserNameToNickName(bizEducateVOList,sysUserMapper.selectUserList(sysUser),"createBy");
            return bizEducateVOList;
        }else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<BizEducate> selectBizEducateListForApp(BizEducate bizEducate,String userName) {
        //班前教育列表
        List<BizEducate> bizEducates = bizEducateMapper.selectBizEducateList(bizEducate);
        if(bizEducates.size() > 0){
            //现场照片ID集合
            Set<Long> photoAttachIds = new HashSet<>();
            bizEducates.stream().forEach(item->{
                if(StringUtils.isNotEmpty(item.getPhotoName())){
                    String[] photoIds = item.getPhotoName().split(",");
                    for (int i = 0; i < photoIds.length; i++) {
                        photoAttachIds.add(Long.valueOf(photoIds[i]));
                    }
                }
            });
            if(photoAttachIds.size() > 0){
                Map<Long,BizEducateDocAttachVO> photoBizEducateDocAttachMap = new HashMap<>();
                //现场照片集合
                List<BizEducateDocAttachVO> photoBizEducateDocAttaches = bizEducateDocAttachService.selectBizEducateDocAttachByIds(photoAttachIds.toArray(new Long[]{}));
                photoBizEducateDocAttachMap.putAll(photoBizEducateDocAttaches.stream().collect(Collectors.toMap(BizEducateDocAttachVO::getId,Function.identity())));
                //补充照片信息
                bizEducates.stream().forEach(item -> {
                    if (StringUtils.isNotEmpty(item.getPhotoName())) {
                        List<BizEducateDocAttachVO> photoBizEducateDocAttaches1 = new ArrayList<>();
                        String[] photoAttachIds1 = item.getPhotoName().split(",");
                        for (int i = 0; i < photoAttachIds1.length; i++) {
                            BizEducateDocAttachVO bizEducateDocAttach =  photoBizEducateDocAttachMap.get(Long.valueOf(photoAttachIds1[i]));
                          if(bizEducateDocAttach != null){
                              photoBizEducateDocAttaches1.add(bizEducateDocAttach);
                          }
                        }
                        item.setPhotoBizEducateDocAttachList(photoBizEducateDocAttaches1);
                    } else {
                        item.setPhotoBizEducateDocAttachList(new ArrayList<>());
                    }
                });
            }
            bizEducates.forEach(item->{
                if(item.getCreateBy().equals(userName)){
                    item.setCanDelete(true);
                }else{
                    item.setCanDelete(false);
                }
            });
            Set<String> bizEducateCreateBys = bizEducates.stream().map(item->item.getCreateBy()).collect(Collectors.toSet());
            //补充班前教育创建人
            SysUser sysUser = new SysUser();
            sysUser.setUserNames(bizEducateCreateBys);
            NameUtils.handleUserNameToNickName(bizEducates,sysUserMapper.selectUserList(sysUser),"createBy");
        }
        return bizEducates;
    }

    /**
     * 新增班前教育
     *
     * @param bizEducate 班前教育
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBizEducate(BizEducate bizEducate) {
        bizEducate.setCreateTime(DateUtils.getNowDate());
        bizEducate.setCreateBy(SecurityUtils.getUsername());
        List<BizEducateDocAttachVO> bizEducateDocAttaches = bizEducate.getFileBizEducateDocAttachList();
        if(bizEducateDocAttaches != null){
            bizEducateDocAttaches.forEach(bizEducateDocAttach -> {
                bizEducateDocAttachMapper.updateBizEducateDocAttach(bizEducateDocAttach);
            });
            List<String> bizEducateDocAttacheIds = bizEducateDocAttaches.stream().map(bizEducateDocAttache->String.valueOf(bizEducateDocAttache.getId())).collect(Collectors.toList());
            String fileName = String.join(",",bizEducateDocAttacheIds);
            bizEducate.setFileName(fileName);
        }
        int rows = bizEducateMapper.insertBizEducate(bizEducate);
        insertBizEducateClass(bizEducate);
        return rows;
    }

    @Override
    public int insertBizEducateNoLogin(BizEducate bizEducate) {
        int rows = bizEducateMapper.insertBizEducate(bizEducate);
        insertBizEducateClass(bizEducate);
        return rows;
    }

    /**
     * 修改班前教育
     *
     * @param bizEducate 班前教育
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBizEducate(BizEducate bizEducate) {
        bizEducate.setUpdateTime(DateUtils.getNowDate());
        bizEducateMapper.deleteBizEducateClassByEducateId(bizEducate.getId());
        insertBizEducateClass(bizEducate);
        return bizEducateMapper.updateBizEducate(bizEducate);
    }

    @Override
    @Transactional
    public int updateBizEducateNoLogin(BizEducate bizEducate) {
        bizEducateMapper.deleteBizEducateClassByEducateId(bizEducate.getId());
        insertBizEducateClass(bizEducate);
        return bizEducateMapper.updateBizEducate(bizEducate);
    }

    /**
     * 批量删除班前教育
     *
     * @param ids 需要删除的班前教育主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBizEducateByIds(Long[] ids) {
        bizEducateMapper.deleteBizEducateClassByEducateIds(ids);
        return bizEducateMapper.deleteBizEducateByIds(ids);
    }

    /**
     * 删除班前教育信息
     *
     * @param id 班前教育主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBizEducateById(Long id) {
        bizEducateMapper.deleteBizEducateClassByEducateId(id);
        return bizEducateMapper.deleteBizEducateById(id);
    }
    /**
     * 新增教育班级关联信息
     *
     * @param bizEducate 班前教育对象
     */
    public void insertBizEducateClass(BizEducate bizEducate) {
        List<BizEducateClass> bizEducateClassList = bizEducate.getBizEducateClassList();
        Long id = bizEducate.getId();
        if (StringUtils.isNotNull(bizEducateClassList)) {
            List<BizEducateClass> list = new ArrayList<>();
            for (BizEducateClass bizEducateClass : bizEducateClassList){
                bizEducateClass.setEducateId(id);
                list.add(bizEducateClass);
            }
            if (!list.isEmpty()) {
                bizEducateMapper.batchBizEducateClass(list);
            }
        }
    }
}
